<template>
    <div class="user-management">
      <el-card class="box-card">
        
  
        <!-- 查询表单 -->
        <el-form inline>
          <el-form-item label="姓名">
            <el-input v-model="search.name" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="search.idCard" placeholder="请输入身份证号" clearable />
          </el-form-item>
          <el-form-item label="部门">
            <el-input v-model="search.department" placeholder="请输入部门" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="search.status" placeholder="请选择状态" clearable>
              <el-option label="激活" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="search.role" placeholder="请选择角色" clearable>
              <el-option
                v-for="item in roles"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchUserList">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="openAddUserDialog">新增用户</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 用户列表 -->
        <el-table :data="userList" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="idCard" label="身份证号" width="180" />
          <el-table-column prop="gender" label="性别" width="80" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="address" label="地址" width="200" />
          <el-table-column prop="phone" label="联系电话" width="150" />
          <el-table-column prop="role" label="角色" width="100" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="text" @click="openEditUserDialog(scope.row)">编辑</el-button>
              <el-button type="text" @click="deleteUser(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
  
      <!-- 新增用户对话框 -->
      <el-dialog v-model="addUserDialogVisible" title="新增用户">
        <el-form ref="addUserForm" :model="newUser" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="newUser.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="newUser.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="newUser.gender" placeholder="请选择性别">
              <el-option label="男" value="male" />
              <el-option label="女" value="female" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="newUser.department" placeholder="请输入部门" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="newUser.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="newUser.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="newUser.role" placeholder="请选择角色">
              <el-option
                v-for="item in roles"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="newUser.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="newUser.status" placeholder="请选择状态">
              <el-option label="激活" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker v-model="newUser.createTime" type="datetime" placeholder="选择创建时间" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 编辑用户对话框 -->
      <el-dialog v-model="editUserDialogVisible" title="编辑用户">
        <el-form ref="editUserForm" :model="editUser" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="editUser.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="editUser.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="editUser.gender" placeholder="请选择性别">
              <el-option label="男" value="male" />
              <el-option label="女" value="female" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="editUser.department" placeholder="请输入部门" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editUser.address" placeholder="请输入地址" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editUser.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="editUser.role" placeholder="请选择角色">
              <el-option
                v-for="item in roles"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUser.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="editUser.status" placeholder="请选择状态">
              <el-option label="激活" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker v-model="editUser.createTime" type="datetime" placeholder="选择创建时间" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref } from "vue";
  import { ElMessage } from "element-plus";
  import axios from "axios";
  import request from '../utils/request';
  
  export default {
    setup() {

        
      const userList = ref([
        {
          id: 1,
          name: "张三",
          idCard: "123456789012345678",
          gender: "male",
          department: "技术部",
          address: "北京市朝阳区",
          phone: "13800138000",
          role: "admin",
          email: "zhangsan@example.com",
          status: "active",
          createTime: new Date(),
        },
        {
          id: 2,
          name: "李四",
          idCard: "098765432109876543",
          gender: "female",
          department: "市场部",
          address: "上海市浦东新区",
          phone: "13900139000",
          role: "user",
          email: "lisi@example.com",
          status: "disabled",
          createTime: new Date(),
        },
      ]);


      
  
      const currentPage = ref(1);
      const pageSize = ref(5);
      //const total = ref(userList.value.length);
       const total = ref(userList.value.length);
  
      const search = ref({
        name: "",
        idCard: "",
        department: "",
        status: "",
        role: "",
      });
  
      // 模拟从后端获取的角色数据
      const roles = ref([
        { label: "管理员", value: "admin" },
        { label: "普通用户", value: "user" },
        { label: "审核员", value: "reviewer" },
        { label: "财务", value: "finance" },
      ]);
  
      const addUserDialogVisible = ref(false);
      const editUserDialogVisible = ref(false);
  
      const newUser = ref({
        name: "",
        idCard: "",
        gender: "male",
        department: "",
        address: "",
        phone: "",
        role: "user",
        email: "",
        status: "active",
        createTime: new Date(),
      });
  
      const editUser = ref({});
  
      const openAddUserDialog = () => {
        addUserDialogVisible.value = true;
      };
  
      const openEditUserDialog = (user) => {
        editUser.value = { ...user };
        editUserDialogVisible.value = true;
      };
  
      const addUser1 = () => {
        const newUserId = Math.max(...userList.value.map((u) => u.id)) + 1;
        newUser.value.id = newUserId;
        userList.value.push(newUser.value);
        newUser.value = {
          name: "",
          idCard: "",
          gender: "male",
          department: "",
          address: "",
          phone: "",
          role: "user",
          email: "",
          status: "active",
          createTime: new Date(),
        };
        addUserDialogVisible.value = false;
        ElMessage.success("用户添加成功");
      };

      const addUser = async () => {
      try {
        await request.post("/user/usermanagement/add", newUser.value);
        ElMessage.success("用户添加成功");
        addUserDialogVisible.value = false;
        await fetchUserList();
      } catch (error) {
        ElMessage.error("用户添加失败");
        console.error("新增用户失败", error);
      }
    };

      
  
      const updateUser1 = () => {
        const index = userList.value.findIndex((u) => u.id === editUser.value.id);
        if (index !== -1) {
          userList.value[index] = { ...editUser.value };
        }
        editUserDialogVisible.value = false;
        ElMessage.success("用户信息更新成功");
      };

       // 更新用户
    const updateUser = async () => {
      try {
        await request.put("/user/usermanagement/update", editUser.value);
        ElMessage.success("用户更新成功");
        editUserDialogVisible.value = false;
        await fetchUserList();
      } catch (error) {
        ElMessage.error("用户更新失败");
        console.error("更新用户失败", error);
      }
    };


  
      const deleteUser1 = (id) => {
        const index = userList.value.findIndex((u) => u.id === id);
        if (index !== -1) {
          userList.value.splice(index, 1);
          ElMessage.success("用户删除成功");
        }
      };

      // 删除用户
    const deleteUser = async (id) => {
      try {
        await request.delete(`/user/usermanagement/delete/${id}`);
        ElMessage.success("用户删除成功");
        await fetchUserList();
      } catch (error) {
        ElMessage.error("用户删除失败");
        console.error("删除用户失败", error);
      }
    };
  
 // 获取用户列表
    const fetchUserList = async () => {
        debugger;
      try {
        const params = {
          name: search.value.name,
          idCard: search.value.idCard,
          department: search.value.department,
          status: search.value.status,
          role: search.value.role,
        };
        const response = await request.get("/user/usermanagement/list", params);
        userList.value = response.data;
        //total.value = response.data.size;
        total.value = 20;
      } catch (error) {
        console.error("获取用户列表失败", error);
      }
    };

      const fetchUserList1 = () => {
        let filteredList = userList.value;
  
        if (search.value.name) {
          filteredList = filteredList.filter((user) =>
            user.name.includes(search.value.name)
          );
        }
        if (search.value.idCard) {
          filteredList = filteredList.filter((user) =>
            user.idCard.includes(search.value.idCard)
          );
        }
        if (search.value.department) {
          filteredList = filteredList.filter((user) =>
            user.department.includes(search.value.department)
          );
        }
        if (search.value.status) {
          filteredList = filteredList.filter((user) => user.status === search.value.status);
        }
        if (search.value.role) {
          filteredList = filteredList.filter((user) => user.role === search.value.role);
        }
  
        userList.value = filteredList;
      };
  
      const resetSearch = () => {
        search.value = {
          name: "",
          idCard: "",
          department: "",
          status: "",
          role: "",
        };
        fetchUserList();
      };
  
      const handleSizeChange = (newSize) => {
        pageSize.value = newSize;
      };
  
      const handleCurrentChange = (newPage) => {
        currentPage.value = newPage;
      };

       // 初始化
    //fetchRoles();
    fetchUserList();
  
      return {
        userList,
        currentPage,
        pageSize,
        total,
        search,
        roles,
        addUserDialogVisible,
        editUserDialogVisible,
        newUser,
        editUser,
        openAddUserDialog,
        openEditUserDialog,
        addUser,
        updateUser,
        deleteUser,
        fetchUserList,
        resetSearch,
        handleSizeChange,
        handleCurrentChange,
      };
    },
  };
  </script>
  
  <style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  </style>